<?php

namespace App\Http\Controllers\front;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;


class LoginController extends Controller
{
    /**
     * 数据列表接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request)
    {


        /**
         *  @api
         * 只处理数据 增删改查  只告诉前端、他这个请求是否成功
         * 不管页面跳转、页面
         */

        // 预处理
        $page = $request->input('page',1);
        $size = $request->input('limit',10);
        $offset =  ($page - 1 ) * $size;

        // 获取列表
        $data = DB::select("SELECT id,title,author,category,content FROM `article` LIMIT ?,?",[$offset,$size]);
        // 查询总数
        $count = DB::select("SELECT count(id) as count  FROM `article`");
        // 返回数据
        $data = [
            'code' => 0,
            'data' => $data,
            'count' => $count[0]->count,
            'msg' => 'ok',
        ];
        return response()->json($data);
    }

    /**
     * 添加文章借口
     */
    public function add(Request $request){
        // 接值
        $title    = $request->get('title');
        $author   = $request->get('author');
        $category = $request->get('category');
        $desc     = $request->get('desc');

        DB::table('article')->insert([
            'title'    =>  $title,
            'author'   =>  $author,
            'category' =>  $category,
            'content'  =>  $desc,
        ]);
    }

    /**
     * 删除元素
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function del(Request $request) {
        $id = $request->post('id');

        // 获取列表
        $data = DB::select("DELETE FROM `article` WHERE  id = ?",[$id]);
        // 返回数据
        $data = [
            'code' => 0,
            'data' => [],
            'msg' => 'ok',
        ];
        return response()->json($data);
    }

    /**
     * 编辑文章
     */
    public function editor(Request $request){

        // 接值
        $id    = $request->get('id');
        $title    = $request->get('title');
        $author   = $request->get('author');
        $category = $request->get('category');
        $desc     = $request->get('desc');
        $data = [
            'title' => $title,
            'author' => $author,
            'category' => $category,
            'desc' => $desc,
        ];
        $result = DB::update("UPDATE `article` SET title = '{$title}', author = '{$author}',category = '{$category}',content = '{$desc}' WHERE id = ?",[$id]);
        if ($result) {
            // 返回数据
            $data = [
                'code' => 0,
                'data' => [],
                'msg' => '修改成功',
            ];
        } else {
            // 返回数据
            $data = [
                'code' => 3001,
                'data' => [],
                'msg' => '修改失败',
            ];
        }

        return response()->json($data);
    }
}
